﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 代码积累.DotNet.Utilities.获得各种类型的Key和value
{
    class GetKey
    {
        /// <summary>
        /// List获得子集合的KEY值
        /// </summary>
        /// <typeparam name="T">集合类型</typeparam>
        /// <param name="data">List集合</param>
        /// <returns></returns>
        public static string GetListkey<T>(List<T> data)
        {
            //获取data的类型值
            Type type = data.GetType();
            //得到list每一项的类型
            Type[] genericArgTypes = type.GetGenericArguments();
            //得到当前一项的整体
            System.Reflection.PropertyInfo[] properties = genericArgTypes[0].GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            var re = "";
            var a = 0;
            foreach (System.Reflection.PropertyInfo item in properties)
            {
                //当前类型的KEY值
                string key = item.Name;
                if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                {
                    if (a == 0)
                    {
                        re = key;
                    }
                    else
                    {
                        re = re + "|" + key;
                    }

                }
            }
            return re;
        }
        /// <summary>
        /// DataTable获得key值
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns></returns>
        public static string GetDataTableKey(DataTable data)
        {

            var re = "";
            if (data.Columns.Count > 0)
            {
                for (int i = 0; i < data.Columns.Count; i++)
                {
                    var key = data.Columns[i].ColumnName;
                    if (i==0)
                    {
                        re = key;
                    }else
                    {
                        re=re+"|"+ key;
                    }
                }
            }
            return re;
        }
    }
}
